#coding=utf-8
#author:dn_李四海(qq:653378495)
#动脑学院VIP
# 1.基于tcp协议socket套接字编程半双工模式
##客户端
# import socket
#
# s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#
# s.connect(('127.0.0.1',9999))
#
# print(s.recv(1024))
#
# for data in ['Michael','Tracy','Sarah']:
#     s.send(data.encode())
#     print(s.recv(1024))
#
# s.send(b'exit')
#
# ##服务器
# import socket
# import time
# import threading
#
#
# def tcplink(sock, addr):
#     print("accept new connection from %s:%s..." % addr)
#     sock.send("Welcom!".encode())
#     while True:
#         data = sock.recv(1024)
#         time.sleep(1)
#         if data == 'exit' or not data:
#             break
#         sock.send("hello: ".encode() + data)
#     sock.close()
#     print("Connection from %s:%s closed." % addr)
#
#
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 创建一个基于ipv4 的TCP协议的socket
#
# s.bind(('127.0.0.1', 9999))  # 监听端口
#
# s.listen(5)
# print("Waiting for connection......")
#
# while True:
#     sock, addr = s.accept()
#     t = threading.Thread(target=tcplink, args=(sock, addr))
#     t.start()


# 2.socketserver异步非阻塞编程,编写代码
## 客户端
from socket import *

host = '127.0.0.1'
port = 8001
addr = (host, port)
BUF_SIZE = 1024

client = socket(AF_INET, SOCK_STREAM)
client.connect(addr)

while True:
    data = raw_input()
    if data.strip() == 'exit':
        break
    if not data:
        continue client.send('%s\r\n' % data)
    print("send:%s" % data)
    dataRecv = client.recv(BUF_SIZE)
    print("recv:%s" % dataRecv)
client.close()
## 服务器
import SocketServer
from SocketServer import StreamRequestHandler
from time import ctime
host = '127.0.0.1'
port = 8001
addr = (host, port)
BUF_SIZE = 1024
class Servers(StreamRequestHandler):
    def handle(self):
        print
        'connection from %s' % str(self.client_address)
        # self.wfile.write('connection %s:%s at %s succeed!' % (host,port,ctime()))
        while True:
            try:
                data = self.request.recv(1024)
                if not data:
                    break
                print
                "----\n%s\n[Recv]%s" % (str(self.client_address), data)
                self.request.send(data)
            except:
                break
        print("disconnect %s" % str(self.client_address))
print('server is running....')
server = SocketServer.ThreadingTCPServer(addr, Servers)
server.serve_forever()